package br.com.bibliotech.dao;

import br.com.bibliotech.dao.interfaces.IDao;
import br.com.bibliotech.entity.Aluno;
import br.com.bibliotech.util.PersistenceFactory;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;

/**
 *
 * @author kamilla
 */
public class AlunoDao implements IDao {

    @Override
    public void add(Aluno aluno) {
        EntityManager manager = null;
        try {
            manager = PersistenceFactory.getEntityManager();
            manager.getTransaction().begin();
            manager.persist(aluno);
            manager.getTransaction().commit();            
        } catch (Exception e) {
            manager.getTransaction().rollback();
        } finally {
            manager.close();
        }
    }

    public void remove(Aluno aluno) {
        EntityManager manager = null;
        try {
            manager = PersistenceFactory.getEntityManager();
            manager.getTransaction().begin();
            Aluno a = manager.merge(aluno);
            manager.remove(a);
            manager.getTransaction().commit();
        } catch (Exception e) {
            e.printStackTrace();
            manager.getTransaction().rollback();
        } finally {
            manager.close();
        }
    }

    @Override
    public void update(Aluno aluno) {
        throw new UnsupportedOperationException("Not supported yet.");
    }
    
    public Aluno pesquisarPorMatricula(String matricula) {
        EntityManager manager = null;
        Aluno aluno = null;
        try {
            manager = PersistenceFactory.getEntityManager();
            Query query = manager.createNamedQuery("Pessoa.buscarPessoaPorMatricula");
            // Setando o parametro acpfr para a consulta, o valor recebera o cpf a ser buscado
            query.setParameter("valor", matricula);
            aluno = (Aluno) query.getSingleResult();
            if (aluno != null) {
                return aluno;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return aluno;
    }
    
    public List<Aluno> listarPorNome(String nome) {
        EntityManager manager = null;
        List<Aluno> alunos = null;
        try {
            manager = PersistenceFactory.getEntityManager();
            Query query = manager.createNamedQuery("Pessoa.buscarPessoaPorNome");
            // Setando o parametro acpfr para a consulta, o valor recebera o cpf a ser buscado
            query.setParameter("valor", '%' + nome + '%');
            alunos = query.getResultList();
            if (alunos != null) {
                return alunos;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return alunos;
    }    
}
